package com.qidian.common;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.qidian.common.beanCache.AccountBeanCache;
import com.qidian.common.beanCache.ClientBeanCache;
import com.qidian.common.beanCache.GameTypeBeanCache;
import com.qidian.common.beanCache.MessageBeanCache;
import com.qidian.common.beanCache.RechargeCardBeanCache;
import com.qidian.common.beanCache.UserBeanCache;
import com.qidian.common.beans.AccountBean;
import com.qidian.common.beans.AnswerType;
import com.qidian.common.beans.ClientBean;
import com.qidian.common.beans.GameTypeBean;
import com.qidian.common.beans.LoggerRecordBean;
import com.qidian.common.beans.MessageBean;
import com.qidian.common.beans.RechargeCardBean;
import com.qidian.common.beans.StasticClientBean;
import com.qidian.common.beans.UserBean;
import com.qidian.connection.util.ConnectionPool;
import com.qidian.server.socket.AnswerServer;
import com.qidian.server.socket.FileServer;
import com.qidian.server.workerThread.Stastic_Client;
import com.qidian.server.workerThread.Synchronizer_Account;
import com.qidian.server.workerThread.Synchronizer_Client;
import com.qidian.server.workerThread.Synchronizer_Message;
import com.qidian.server.workerThread.Synchronizer_RechargeCard;
import com.qidian.server.workerThread.Synchronizer_User;
import com.qidian.util.PageInfo;
import com.qidian.util.PageList;
import com.qidian.util.StringUtil;

/**
 * 	全局共享对象，如消息缓冲区
 * 
 * */
public final class Globals 
{

	private static Logger logger = LogManager.getLogger(Globals.class);
	
    public static String uploadDirAbsolutePath = null ;
    public static String uploadDirRelativePath = "temp/" ;
	public static String globals = null ;
	public static volatile IDGenerator msgIdG = null ;
	
	/*	缓存	*/
	public static MessageBeanCache mbb = null ;
	public static ClientBeanCache cbb = null ;
	public static AccountBeanCache abb = null ;
	public static UserBeanCache 	ubb = null ;
	public static GameTypeBeanCache gtc = null ;
	public static RechargeCardBeanCache rcc = null ;
	
	/*	同步线程	*/
	private static Synchronizer_Message ms ;
	private static Synchronizer_Client cs ;
	private static Synchronizer_User us ;
	private static Synchronizer_Account as ;
	private static Synchronizer_RechargeCard rs ;
	
	/*	统计线程	*/
	private static Stastic_Client sc ;
	
//	private static FileServer fileServer_ctc = null ;
//	private static FileServer fileServer_cucc = null ;
//	private static AnswerServer answerServer_ctc = null ;
//	private static AnswerServer answerServer_cucc = null ;
	
	private static volatile AtomicBoolean initFlag = new AtomicBoolean(false) ;
	static 
	{
//		System.out.println("Init time") ;
//		System.out.println(Thread.currentThread().getContextClassLoader());
		if(!initFlag.getAndSet(true))
		{
			if (!initGlobals())
				System.exit(-1) ;
			initFlag.set(true) ;
		}
		
	}
	
	
	/**
	 * 初始化所有的全局对象。
	 * @throws Exception 
	 * 
	 * */
	private static boolean initGlobals()
	{
		
		// 本地化设置
		Locale.setDefault(Locale.CHINESE) ;
		
		// 创建库表
		if (!createTables())
			return false ;
		
		//初始化全局对象
		if (!initMessageIDGenerator())
			return false ;
		if (!initMessageBuffer())
			return false ;
		if (!initClientBuffer())
			return false ;
		if (!initAccountBuffer())
			return false ;
		if (!initUserBuffer())
			return false ;
		if (!initGameTypeBuffer())
			return false ;
		if (!initRechargeCardBuffer())
			return false ;
		
		//启动同步线程
		ms = Synchronizer_Message.getInstance() ;
		ms.start() ;
		cs = Synchronizer_Client.getInstance() ;
		cs.start() ;
		us = Synchronizer_User.getInstance() ;
		us.start() ;
		as = Synchronizer_Account.getInstance() ;
		as.start() ;
		rs = Synchronizer_RechargeCard.getInstance() ;
		rs.start() ;
		
		// 启动统计线程
		sc = Stastic_Client.getInstance() ;
		sc.start() ;
		
//		// 启动文件接收线程，如果双IP，则分别启动
//		if (Constants.portSendFile > 0)
//		{
//			fileServer_ctc = new FileServer(Constants.localIP_CTC,Constants.portSendFile) ;
//			fileServer_ctc.start() ;
//			if (Constants.localIP_CUCC != null && !Constants.localIP_CUCC.equalsIgnoreCase(Constants.localIP_CTC))
//			{
//				fileServer_cucc = new FileServer(Constants.localIP_CUCC,Constants.portSendFile) ;
//				fileServer_cucc.start() ;
//			}
//		}
//		// 启动答案查询线程，如果双IP，则分别启动
//		if (Constants.portGetAnswer > 0)
//		{
//			answerServer_ctc = new AnswerServer(Constants.localIP_CTC,Constants.portGetAnswer) ;
//			answerServer_ctc.start() ;
//			if (Constants.localIP_CUCC != null && !Constants.localIP_CUCC.equalsIgnoreCase(Constants.localIP_CTC))
//			{
//				answerServer_cucc = new AnswerServer(Constants.localIP_CUCC,Constants.portGetAnswer) ;
//				answerServer_cucc.start() ;
//			}
//		}
//		// 系统消息服务线程
//		if (Constants.startSysInfoServer)
//		{
//			sis = new SysInfoServer() ;
//			sis.start();
//		}
		
		// 创建超级用户
		if(ubb.getByUserName(Constants.super_user_name) == null)
			newUserBean(Constants.super_user_name,Constants.super_password,Integer.MAX_VALUE,
					Constants.super_qq,Constants.super_email,"","",0,0.0) ;
		
		return true ;
	}
	private static boolean createTables()
	{
		Connection conn = null ;
		try
		{
			// 初始化库表
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			stt.executeUpdate(TableMeta.create_client_table) ;
			stt.executeUpdate(TableMeta.create_user_table) ;
			stt.executeUpdate(TableMeta.create_game_type_table) ;
			stt.executeUpdate(TableMeta.create_message_table) ;
			stt.executeUpdate(TableMeta.create_account_table) ;
			stt.executeUpdate(TableMeta.create_recharge_card_table) ;
			stt.executeUpdate(TableMeta.create_logger_table) ;
			stt.executeUpdate(TableMeta.create_stastic_client_table) ;
			stt.close() ;
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			System.out.println("初始化数据库表失败!") ;
			return false ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return true ;
	}
	/**
	 * 初始化当前的ID
	 * 
	 * */
	private static boolean initMessageIDGenerator()
	{
    	// 从数据库中初始化用户信息
    	Connection conn = null ;
    	try
    	{
    		conn = ConnectionPool.getConnection() ;
    		Statement stt = conn.createStatement() ;
    		
    		ResultSet rs = stt.executeQuery("select max("+TableMeta.column_msg_id+") from " + TableMeta.table_message) ;
    		if (rs.next())
    			msgIdG = new IDGenerator(rs.getLong(1)+10000,1) ;
    		else
    			msgIdG = new IDGenerator(0+100000,1) ;
    		rs.close() ;
    		stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return false ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}		
		return true ;
	}
	private static boolean initMessageBuffer()
	{
		mbb = MessageBeanCache.getInstance() ;
		return true ;
	}
	private static boolean initClientBuffer()
	{
		cbb = ClientBeanCache.getInstance() ;
		
    	// 从数据库中初始化客户端信息
    	Connection conn = null ;
    	try
    	{
    		conn = ConnectionPool.getConnection() ;
    		Statement stt = conn.createStatement() ;
    		
    		// 缓存客户端信息
    		ResultSet rs = stt.executeQuery("select * from " + TableMeta.table_client+ " where " + TableMeta.column_status + " >= 0") ;
    		while(rs.next())
    		{
    			ClientBean clientBean = ClientBean.toClientBean(rs) ;
    			cbb.add(clientBean) ;
    		}
    		rs.close() ;
    		
    		// 更新统计信息
    		Date today = new Date() ;
    		rs = stt.executeQuery("select * from "+ TableMeta.table_stastic_client +
    				" where " + TableMeta.column_day + " = '" + StringUtil.toDateString(today)+"'");
    		while(rs.next())
    		{
    			long clientId = rs.getLong(TableMeta.column_client_id) ;
    			ClientBean clientBean = cbb.getClient(clientId) ;
    			if (clientBean == null)
    				continue ;
    			clientBean.setAnsweredYesterday(rs.getInt(TableMeta.column_answer_count_yesterday)) ;
    			clientBean.setWrongYesterday(rs.getInt(TableMeta.column_wrong_count_yesterday)) ;
    			clientBean.setPointYesterday(rs.getDouble(TableMeta.column_point_yesterday)) ;
    		}
    		rs.close() ;
    			
    		
    		stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return false ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}		
		return true ;
	}
	private static boolean initUserBuffer()
	{
		ubb = UserBeanCache.getInstance() ;
		
    	// 从数据库中初始化用户信息
    	Connection conn = null ;
    	try
    	{
    		conn = ConnectionPool.getConnection() ;
    		Statement stt = conn.createStatement() ;
    		
    		ResultSet rs = stt.executeQuery("select * from " + TableMeta.table_user + " where " + TableMeta.column_status + " >= 0") ;
    		while(rs.next())
    		{
    			UserBean userBean = UserBean.toUserBean(rs) ;
    			ubb.add(userBean) ;
    		}
    		rs.close() ;
    		stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return false ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}
    			
		return true ;
	}	
	private static boolean initAccountBuffer()
	{
		abb = AccountBeanCache.getInstance() ;
		
    	// 从数据库中初始化用户信息
    	Connection conn = null ;
    	try
    	{
    		conn = ConnectionPool.getConnection() ;
    		Statement stt = conn.createStatement() ;
    		
    		ResultSet rs = stt.executeQuery("select * from " + TableMeta.table_account 
    				+ " where " + TableMeta.column_status + " >= 0") ;
    		while(rs.next())
    		{
    			AccountBean userBean = AccountBean.toAccountBean(rs) ;
    			abb.add(userBean) ;
    		}
    		rs.close() ;
    		stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return false ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}
    			
		return true ;
	}
	private static boolean initGameTypeBuffer()
	{
		gtc = GameTypeBeanCache.getInstance() ;
		
    	// 从数据库中初始化用户信息
    	Connection conn = null ;
    	try
    	{
    		conn = ConnectionPool.getConnection() ;
    		Statement stt = conn.createStatement() ;
    		
    		ResultSet rs = stt.executeQuery("select * from " + TableMeta.table_game_type+ " where " + TableMeta.column_status + " >= 0") ;
    		while(rs.next())
    		{
    			GameTypeBean gameTypeBean = GameTypeBean.toGameType(rs) ;
    			gtc.add(gameTypeBean) ;
    		}
    		rs.close() ;
    		stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return false ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}
    	
    	return true ;
	}
	private static boolean initRechargeCardBuffer()
	{
		rcc = RechargeCardBeanCache.getInstance() ;
		
    	// 从数据库中初始化充值卡信息
    	Connection conn = null ;
    	try
    	{
    		conn = ConnectionPool.getConnection() ;
    		Statement stt = conn.createStatement() ;
    		
    		ResultSet rs = stt.executeQuery("select * from " + TableMeta.table_recharge_card + " where " + TableMeta.column_status + " >= 0") ;
    		while(rs.next())
    		{
    			RechargeCardBean userBean = RechargeCardBean.toRechargeCardBean(rs) ;
    			rcc.add(userBean) ;
    		}
    		rs.close() ;
    		stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return false ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}
    			
		return true ;
	}	
	/**
	 * 生成新用户
	 * 1.插入数据库
	 * 2.插入缓存
	 * 
	 * @param userName 开发者用户名
	 * @param password 密码
	 * @param point 点数
	 * @param qq QQ
	 * @param email 
	 * @param zhifubao 支付宝
	 * @param phone 电话
	 * @param userType 开发者类型
	 * @param returnRatio 返点比率
	 * 
	 * */
	public synchronized static UserBean newUserBean(
			String userName, String password, int point,
			String qq, String email,String zhifubao, String phone,int userType,
			double returnRatio)
	{
		if (userName == null || password == null)
			return null ;
		if (!UserBean.isValidPassword(password) || !UserBean.isValidUserName(userName))
			return null ;
		UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
		if (user != null)
			return null ;
		
		Long userId = 0L;
		final String querySql = "select max(" + TableMeta.column_user_id + ") from " + TableMeta.table_user ;
    	Connection conn = null ;
    	long currentTime = System.currentTimeMillis() ;
    	try
    	{
    		long maxId = 0 ;
    		conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
		
			ResultSet rs = stt.executeQuery(querySql) ;
			if (rs.next())
				maxId = rs.getLong(1) ;
			rs.close() ;
			
			/*	插入数据库	*/
			userId = maxId+1 ;
			String insertSql = "insert into " + TableMeta.table_user + " values(" + userId + ",'"+
								userName.toLowerCase()+"','"+password+"',"+point+",0,"+currentTime+","+
								currentTime+",0,'"+qq+"','"+email+"','"+zhifubao+"','"+phone+"',"+
								userType+",0,"+returnRatio+")";
			System.out.println(insertSql) ;
			stt.executeUpdate(insertSql) ;
			stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return null ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}		
    	
    	// 插入缓存
    	user = new UserBean() ;
    	user.setUserId(userId) ;
    	user.setPoint(point) ;
    	user.setUsedPoint(0) ;
    	user.setUserName(userName) ;
    	user.setPassword(password) ;
    	user.setBirthTime(currentTime) ;
    	user.setLastTime(currentTime) ;
    	user.setQQ(qq) ;
    	user.setEmail(email) ;
    	user.setZhifubao(zhifubao) ;
    	user.setPhone(phone) ;
    	user.setReturnRatio(returnRatio) ;
    	Globals.getUserBuffer().add(user) ;
		
		return user ;		
	}

	/**
	 * 生成新账户：如果validTime > 10000*24*60*60*1000，表示生成限定日期的子账号，否则表示生成限定天数的子账号
	 * 1.插入数据库
	 * 2.插入缓存
	 * 
	 * */
	public synchronized static AccountBean newAccountBean( UserBean user, int point, String maskCode, 
			long validTime)
	{
		if (user == null)
			return null ;
		
//		if (user.getLeftPoint() < point)
//			return null ;
		
		Long accountId = 0L;
		long birthTime = System.currentTimeMillis() ;
		long firstTime = 0L ;
		final String querySql = "select max(" + TableMeta.column_account_id + ") from " + TableMeta.table_account ;
    	
		Connection conn = null ;
    	try
    	{
    		long maxId = 0 ;
    		conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
		
			ResultSet rs = stt.executeQuery(querySql) ;
			if (rs.next())
				maxId = rs.getLong(1) ;
			rs.close() ;
		
			
			// 如果是日期形式,第一次使用使用时间设置为生成日期
			if (validTime > Constants.max_day_validity*Constants.millseconds_per_day)
				firstTime = birthTime ;

			/*	插入数据库	*/
			accountId = maxId+1 ;
			String insertSql = "insert into " + TableMeta.table_account + " values(" + accountId + ",'"+maskCode+"',"+
				point+",0,"+user.getUserId()+",0,"+birthTime+","+validTime+",0,0,0,"+firstTime+")";
			System.out.println(insertSql) ;
			stt.executeUpdate(insertSql) ;
			stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return null ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}		
    	
    	// 插入缓存
    	AccountBean account = new AccountBean() ;
    	account.setAccountId(accountId) ;
    	account.setAccount(maskCode) ;
    	account.setPoint(point) ;
    	account.setUsedPoint(0) ;
    	account.setUserId(user.getUserId()) ;
    	account.setLastTime(0L);
    	account.setBirthTime(birthTime) ;
    	account.setValidTime(validTime) ;
    	account.setFirstTime(firstTime) ;
    	
    	// 加入缓存
		abb.add(account) ;
		user.increaseAccount() ;
		
		return account ;
	}	
	
	/**
	 * 生成新账户：如果validTime > 10000*24*60*60*1000，表示生成限定日期的子账号，否则表示生成限定天数的子账号
	 * 1.插入数据库
	 * 2.插入缓存
	 * 
	 * */
	public synchronized static AccountBean newAccountBean( UserBean user, int point, 
			long validTime)
	{
		if (user == null)
			return null ;
		
//		if (user.getLeftPoint() < point)
//			return null ;
		
		Long accountId = 0L;
		long birthTime = System.currentTimeMillis() ;
		long firstTime = 0L ;
		String maskCode = null ;
		final String querySql = "select max(" + TableMeta.column_account_id + ") from " + TableMeta.table_account ;
    	Connection conn = null ;
    	try
    	{
    		long maxId = 0 ;
    		conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
		
			ResultSet rs = stt.executeQuery(querySql) ;
			if (rs.next())
				maxId = rs.getLong(1) ;
			rs.close() ;
			
			// 如果是日期形式,第一次使用使用时间设置为生成日期
			if (validTime > Constants.max_day_validity*Constants.millseconds_per_day)
				firstTime = birthTime ;

			/*	插入数据库	*/
			accountId = maxId+1 ;
			maskCode = user.getUserId()+"S"+random32String()  ;
			String insertSql = "insert into " + TableMeta.table_account + " values(" + accountId + ",'"+maskCode+"',"+
								
			point+",0,"+user.getUserId()+",0,"+birthTime+","+validTime+",0,0,0,"+firstTime+")";
			System.out.println(insertSql) ;
			stt.executeUpdate(insertSql) ;
			stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return null ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}		
    	
    	// 插入缓存
    	AccountBean account = new AccountBean() ;
    	account.setAccountId(accountId) ;
    	account.setAccount(maskCode) ;
    	account.setPoint(point) ;
    	account.setUsedPoint(0) ;
    	account.setUserId(user.getUserId()) ;
    	account.setLastTime(0L);
    	account.setBirthTime(birthTime) ;
    	account.setValidTime(validTime) ;
    	account.setFirstTime(firstTime) ;
    	
    	// 加入缓存
		abb.add(account) ;
		user.increaseAccount() ;
		
		return account ;
	}
	public synchronized static ClientBean newClientBean(String userName, String password,
			String name, String phone) 
	{
		if (userName == null || password == null)
			return null ;
		
		if (!UserBean.isValidPassword(password) || !UserBean.isValidUserName(userName))
			return null ;
		
		ClientBean client = Globals.getClientBuffer().getClientByName(userName) ;
		if (client != null)
			return null ;
		
		Long clientId = 0L;
		final String querySql = "select max(" + TableMeta.column_client_id + ") from " + TableMeta.table_client ;
    	Connection conn = null ;
    	try
    	{
    		long maxId = 0 ;
    		conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
		
			ResultSet rs = stt.executeQuery(querySql) ;
			if (rs.next())
				maxId = rs.getLong(1) ;
			rs.close() ;
			
			/*	插入数据库	*/
			clientId = maxId+1 ;
			//INSERT INTO account VALUES (1,'maskCode001',10000,0,1,true);
			String insertSql = "insert into " + TableMeta.table_client + " values(" + clientId + ",'"+
								userName.toLowerCase()+"','"+password+"',0,0,0,0,'"+name+"','"+phone+"')";
			System.out.println(insertSql) ;
			stt.executeUpdate(insertSql) ;
			stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return null ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}		
    	
    	// 插入缓存
    	client = new ClientBean() ;
    	client.setClientId(clientId) ;
    	client.setClientName(userName) ;
    	client.setPassword(password) ;
    	client.setPhone(phone) ;
    	client.setName(name) ;
		Globals.getClientBuffer().add(client) ;
		
		return client ;		
	}
	/**
	 * 
	 * 
	 * */
	public synchronized static GameTypeBean newGameTypeBean(String gameDescription,
			int answerType,int answerLen, int status ,int point, double point_worker, int min_interval,
			int transOn,double difficulty) 
	{		
		if (gameDescription == null )
			return null ;
		if (gameDescription.indexOf('\'') >= 0)
			return null ;
		
		Long gameTypeId = 0L;
		int gameType =  0 ;
		final String querySql = "select max(" + TableMeta.column_game_type_id + ") from " + TableMeta.table_game_type ;
    	Connection conn = null ;
    	try
    	{
    		long maxId = 0 ;
    		conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
		
			ResultSet rs = stt.executeQuery(querySql) ;
			if (rs.next())
				maxId = rs.getInt(1) ;
			rs.close() ;
			
			/*	插入数据库	*/
			gameTypeId = maxId+1 ;
			gameType = gameTypeId.intValue() + 1000 ;
			
			String insertSql = "insert into " + TableMeta.table_game_type + " values(" + gameTypeId + ","+gameType + ","+
								point+","+point_worker+",'"+gameDescription+"',"+min_interval+
								","+answerType+","+answerLen+","+status+","+transOn+","+difficulty+")";
			System.out.println(insertSql) ;
			stt.executeUpdate(insertSql) ;
			stt.close() ;
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace() ;
    		logger.error(e.getMessage()) ;
    		return null ;
    	}
    	finally
    	{
    		ConnectionPool.freeConn(conn) ;
    	}		
    	
    	// 插入缓存
    	GameTypeBean gameTypeBean = new GameTypeBean() ;
    	gameTypeBean.setGameTypeId(gameTypeId) ;
    	gameTypeBean.setGameType(gameType) ;
    	gameTypeBean.setAnswerType(answerType) ;
    	gameTypeBean.setAnswerLen(answerLen) ;
    	gameTypeBean.setGameDescription(gameDescription) ;
    	gameTypeBean.setMinInterval(min_interval) ;
    	gameTypeBean.setPoint(point) ;
    	gameTypeBean.setPoint_worker(point_worker) ;
    	gameTypeBean.setTransOn(transOn) ;
    	gtc.add(gameTypeBean) ;
		
		return gameTypeBean ;		
	}	

	/**
	 * 创建新的充值卡
	 * 
	 * */
	public synchronized static RechargeCardBean newRechargeCard(UserBean user,
			int point, long validTime) 
	{
		if (user.getLeftPoint() < point)
			return null ;
		
		long birthTime = System.currentTimeMillis() ;
		RechargeCardBean rechargeCard = new RechargeCardBean() ;
		String rechargeCode = random32String() ; 
		rechargeCard.setRechargeCode(rechargeCode) ;
		rechargeCard.setUsed(0) ;
		rechargeCard.setUserId(user.getUserId()) ;
		rechargeCard.setBirthTime(birthTime) ;
		rechargeCard.setValidTime(validTime) ;
		rechargeCard.setPoint(point) ;
		rechargeCard.setStatus(0) ;
		
		// 插入数据库
		String sql = "insert into " + TableMeta.table_recharge_card + " values('"+
					rechargeCode+"',"+point+",0,"+user.getUserId()+","+birthTime+","+validTime+
					",0,0)" ;
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			stt.executeUpdate(sql) ;
			stt.close() ;
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
			return null ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		
		// 插入缓冲区
		rcc.add(rechargeCard) ;
		
		//如果是超级管理员,增加已用点数
		if(isSuperUser(user))
			user.increaseUsedPoint(point) ;
		
		// 增加已创建充值卡次数
		user.increaseRechargeCard() ;
		
		return rechargeCard;
	}	

	public static IDGenerator getIDGenerator() 
	{
		return msgIdG;
	}
	
	public static void regetIDGenerator()
	{
		initMessageIDGenerator() ;
	}

	public static MessageBeanCache getMessageBuffer() 
	{
		return mbb;
	}

	public static ClientBeanCache getClientBuffer() 
	{
		return cbb;
	}

	public static AccountBeanCache getAccountBuffer() 
	{
		return abb;
	}
	public static UserBeanCache getUserBuffer()
	{
		return ubb ;
	}
	public static GameTypeBeanCache getGameTypeBuffer()
	{
		return gtc ;
	}
	public static RechargeCardBeanCache getRechargeCardBuffer()
	{
		return rcc ;
	}
	public static String getUploadDirAbsolutePath()
	{
	    return uploadDirAbsolutePath ;
	}
	public static String getDownloadDirAbsolutePath()
	{
		return uploadDirAbsolutePath ;
	}
	public static void setUploadDirAbsolutePath(String dir)
	{
	    uploadDirAbsolutePath = dir ;
	}
	public static String getUploadRelativePath()
	{
	    return uploadDirRelativePath ;
	}
	/**
	 * 随机32位字符串[a-z0-9]{32,32}
	 * 
	 * */
	public static String random32String()
	{
		return UUID.randomUUID().toString().replace("-", "") ;
	}
	/**
	 * 是否为超级用户
	 * */
	public static boolean isSuperUser(Object userObj)
	{
		if(userObj == null || !(userObj instanceof UserBean) || !((UserBean)userObj).getUserName().equalsIgnoreCase(Constants.super_user_name))
			return false ;
		return true ;
	}
	
	/**
	 * 条件查询账号信息
	 * 
	 * */
	public static PageList getAccountList(Long userId, int pageNo,
		String userName,String account, long min_validTime , long max_validTime, int min_left_point, int max_left_point)	
	{

		if(pageNo <= 0)
			pageNo = 1 ;
		
		List<AccountBean> list = new ArrayList<AccountBean>(10) ;
		PageInfo pageInfo = new PageInfo(0,0);
		PageList pageList = new PageList() ;
		pageList.setList(list) ;
		pageList.setPageInfo(pageInfo) ;
		
		long accountId = -1L ;
			
		Connection conn = null ;
		try
		{

			String sql = "select * from " + TableMeta.table_account ;
			String countSql = " select count(*) from " + TableMeta.table_account ;
			StringBuffer conditionSb = new StringBuffer(1024) ;
//			conditionSb.append(" where " + TableMeta.column_status + " >= 0 ") ;
			conditionSb.append(" where 1=1 ") ;
			
			if (userId > 0)
				conditionSb.append(" and ").append(TableMeta.column_user_id).append(" = ").append(userId) ;
//			if (qUserId > 0)
//				conditionSb.append(" and ").append(TableMeta.column_user_id).append(" = ").append(qUserId) ;
			if (account != null && account.trim().length() > 0)
			{
				AccountBean accountBean = abb.get(account) ;
				if (accountBean == null)
					return pageList ;
				accountId = accountBean.getAccountId() ;
				conditionSb.append(" and ").append(TableMeta.column_account_id).append("= ").append( accountId) ;
			}
			if (userName != null && userName.trim().length() > 0)
			{
				UserBean userBean = ubb.getByUserName(userName) ;
				if (userBean == null)
					return pageList ;
				Long qUserId = userBean.getUserId() ;
				conditionSb.append(" and ").append(TableMeta.column_user_id).append(" = ").append(qUserId) ;
			}			
			if (min_validTime > 0)
				conditionSb.append(" and ").append(TableMeta.column_valid_time).append(" >= ").append(min_validTime);
			if (max_validTime > 0)
				conditionSb.append(" and ").append(TableMeta.column_valid_time).append(" <= ").append(max_validTime);
			if (min_left_point > 0)
				conditionSb.append(" and ").append(TableMeta.column_point).append(" - ").append(TableMeta.column_point_used).append(" >= ").append(min_left_point);
			if (max_left_point > 0)
				conditionSb.append(" and ").append(TableMeta.column_point).append(" - ").append(TableMeta.column_point_used).append(" <= ").append(max_left_point);
			conditionSb.append(" order by ").append(TableMeta.column_account_id);
			String condition = conditionSb.toString() ;
			countSql +=  condition;
			sql += condition ;
			
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			int total = 0 ;
			ResultSet rs = null ;
			rs = stt.executeQuery(countSql) ;
			if (rs.next())
				total = rs.getInt(1) ;
			rs.close() ;

			pageInfo.setMaxRowCount(total) ;
			pageInfo.setCurPage(pageNo) ;
			pageInfo.setMaxPage((total+PageInfo.PAGESIZE-1)/PageInfo.PAGESIZE);
			int start = PageInfo.PAGESIZE*(pageNo-1) ;
			int end = PageInfo.PAGESIZE*pageNo ;
			rs = stt.executeQuery(sql) ;
			AccountBean accountBean = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count < (end-start))
			{
//				accountBean = abb.get(rs.getString(1));
				accountBean = AccountBean.toAccountBean(rs) ;
				if (accountBean != null)
				{
					list.add(accountBean) ;
					count ++ ;
				}
				
			}
			rs.close() ;
			stt.close() ;
			
			pageList.setList(list) ;
			pageList.setPageInfo(pageInfo) ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return pageList ;		
	}

	public static PageList getAccountList(Long userId, int pageNo)
	{
		pageNo = pageNo<=0?1:pageNo ;
		LinkedList<AccountBean> accountList = new LinkedList<AccountBean>() ;
	    PageList pageList = new PageList() ;

		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select * from " + TableMeta.table_account +
							" where " + TableMeta.column_user_id + " = "+userId+
							" order by " + TableMeta.column_account_id;
			
			String countSql = "select count(*) from " + TableMeta.table_account +
							" where " + TableMeta.column_user_id + " = "+userId+
							" order by " + TableMeta.column_account_id;
			int total = 0 ;
			ResultSet rs = stt.executeQuery(countSql) ;
			if (rs.next())
				total = rs.getInt(1) ;
			rs.close() ;
			PageInfo pageInfo = new PageInfo(pageNo,total) ;
			
	        int start = (pageNo-1)*PageInfo.PAGESIZE ;
	        int end = pageNo*PageInfo.PAGESIZE ;
			rs = stt.executeQuery(sql) ;
			AccountBean account = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count < (end-start))
			{
//				account = abb.get(rs.getString(1));
				account = AccountBean.toAccountBean(rs) ;
				if (account != null)
				{
					accountList.add(account) ;
					count ++ ;
				}
				
			}
			rs.close() ;
			stt.close() ;
			
	        pageList.setList(accountList) ;
	        pageList.setPageInfo(pageInfo) ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		
		return pageList ;
	}	
	public static List<AccountBean> getAccountList(Long userId, int start, int end)
	{
		LinkedList<AccountBean> list = new LinkedList<AccountBean>() ;
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select * from " + TableMeta.table_account +
							" where " + TableMeta.column_user_id + " = "+userId+
							" order by " + TableMeta.column_account_id;
			ResultSet rs = stt.executeQuery(sql) ;
			AccountBean account = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count < (end-start))
			{
//				account = abb.get(rs.getString(1));
				account = AccountBean.toAccountBean(rs) ;
				if (account != null)
				{
					list.add(account) ;
					count ++ ;
				}
				
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return list ;
	}
	public static List<ClientBean> getClientList()
	{
		LinkedList<ClientBean> list = new LinkedList<ClientBean>() ;
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select * from " + TableMeta.table_client +
							" order by " + TableMeta.column_client_id;
			ResultSet rs = stt.executeQuery(sql) ;
			ClientBean user = null ;
			while(rs.next())
			{
//				user = cbb.getClient(rs.getLong(1));
				user = ClientBean.toClientBean(rs) ;
				if (user != null)
				{
					list.add(user) ;
				}
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return list ;		
	}
	public static List<MessageBean> getMessageList(Long accountId, 
			long startTime, long endTime ,
			int start, int end)
	{
		LinkedList<MessageBean> list = new LinkedList<MessageBean>() ;
		if (accountId < 0 || startTime < 0 || endTime < 0 || start < 0 || end < 0)
			return list ;
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select * from " + TableMeta.table_message +
							" where " + TableMeta.column_account_id + " = " + accountId  ;
			if (startTime > 0 )
				sql += " and " + TableMeta.column_receive_time + " >= " + startTime ;
			if (endTime > 0)
				sql += " and " + TableMeta.column_receive_time + " <= " + endTime ;
			
			sql += " order by " + TableMeta.column_msg_id + " limit " + end ;
			ResultSet rs = stt.executeQuery(sql) ;
			MessageBean message = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count <(end-start))
			{
				message = MessageBean.toMessageBean(rs) ;
				if (message != null)
				{
					list.add(message) ;
					count ++ ;
				}
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return list ;
	}	
	public static List<GameTypeBean> getGameTypeList()
	{
		LinkedList<GameTypeBean> list = new LinkedList<GameTypeBean>() ;
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select * from " + TableMeta.table_game_type +
							" where " + TableMeta.column_status +
							" >= 0 order by " + TableMeta.column_game_type;
							
			ResultSet rs = stt.executeQuery(sql) ;
			GameTypeBean gameType = null ;
			while(rs.next())
			{
				gameType = GameTypeBean.toGameType(rs) ;
				if (gameType != null)
				{
					list.add(gameType) ;
				}
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return list ;		
	}
	public static List<UserBean> getUserList(int start, int end)
	{
		LinkedList<UserBean> list = new LinkedList<UserBean>() ;
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select * from " + TableMeta.table_user +
							" order by " + TableMeta.column_user_id;
			ResultSet rs = stt.executeQuery(sql) ;
			UserBean user = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count <(end-start))
			{
//				user = ubb.getByUserName(rs.getString(1)) ;
				user = UserBean.toUserBean(rs) ;
				if (user != null)
				{
					list.add(user) ;
					count ++ ;
				}
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return list ;
	}
	
	public static void main(String[] args) throws SQLException
	{
//		UserBean user = newUserBean("user001","pwd001",100000) ;
//		UserBean user = Globals.getUserBuffer().getByUserName(Constants.super_user_name);
//		ClientBean client = newClientBean("client002","pwd002") ;
//		AccountBean account = newAccountBean(user,50000) ;
//		newGameTypeBean(String gameDescription,
//				String answerType, int point, int point_worker, int min_interval) 
	//	GameTypeBean gameType = newGameTypeBean("TLBB","选择题",1,15,5) ;
		logger(System.currentTimeMillis(),"A","B","C","D","A") ;
		System.exit(-1) ;
	}
	
	

	public static int getUserCount() 
	{
		return ubb.size();
	}
	public static int getAccountCount(long userId)
	{
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select count(*) from " + TableMeta.table_account + 
						" where " + TableMeta.column_user_id + " = " + userId ;
			int count = 0 ;
			ResultSet rs = stt.executeQuery(sql) ;
			if (rs.next())
				count = rs.getInt(1) ;
			rs.close() ;
			stt.close() ;
			return count ;
		}
		catch (Exception e)
		{
			e.printStackTrace() ;
			return 0 ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
	}
	public static PageList getRechargeCardList(Long userId, int pageNo,
			String rechargeCard, long minValidTime, long maxValidTime,
			int minLeftPoint, int maxLeftPoint) {
		if(pageNo <= 0)
			pageNo = 1 ;
		
		List<RechargeCardBean> list = new ArrayList<RechargeCardBean>(10) ;
		PageList pageList = new PageList() ;		
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select "+TableMeta.column_recharge_code+" from " + TableMeta.table_recharge_card +
							" where " + TableMeta.column_user_id + " = "+userId + 
							" and " + TableMeta.column_is_used + " = 0 ";
			String countSql = " select count(*) from " + TableMeta.table_recharge_card +
							" where "  + TableMeta.column_user_id + " = "+userId +
							" and " + TableMeta.column_is_used + " = 0 ";
			StringBuffer conditionSb = new StringBuffer(1024) ;
			if (rechargeCard != null && rechargeCard.trim().length() > 0)
				conditionSb.append(" and ").append(TableMeta.column_recharge_code).append("='").append(rechargeCard).append("'") ;
			if (minValidTime > 0)
				conditionSb.append(" and ").append(TableMeta.column_valid_time).append(" >= ").append(minValidTime);
			if (maxValidTime > 0)
				conditionSb.append(" and ").append(TableMeta.column_valid_time).append(" <= ").append(maxValidTime);
			if (minLeftPoint > 0)
				conditionSb.append(" and ").append(TableMeta.column_point).append(" >= ").append(minLeftPoint);
			if (maxLeftPoint > 0)
				conditionSb.append(" and ").append(TableMeta.column_point).append(" <= ").append(maxLeftPoint);
			conditionSb.append(" order by ").append(TableMeta.column_birth_time);
			String condition = conditionSb.toString() ;
			countSql +=  condition;
			sql += condition ;
			

			int total = 0 ;
			ResultSet rs = null ;
			rs = stt.executeQuery(countSql) ;
			if (rs.next())
				total = rs.getInt(1) ;
			rs.close() ;
			PageInfo pageInfo = new PageInfo(pageNo,total) ;
			
			int start = PageInfo.PAGESIZE*(pageNo-1) ;
			int end = PageInfo.PAGESIZE*pageNo ;
			rs = stt.executeQuery(sql) ;
			RechargeCardBean rechargeCardBean = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count < (end-start))
			{
				rechargeCardBean = rcc.get(rs.getString(1));
				if (rechargeCardBean != null)
				{
					list.add(rechargeCardBean) ;
					count ++ ;
				}
				
			}
			rs.close() ;
			stt.close() ;
			
			pageList.setList(list) ;
			pageList.setPageInfo(pageInfo) ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return pageList ;		
	}
	public static PageList getAnswerRecordList(int pageNo, 
			String account,
			boolean filterRight,
			long msgId, 
			int gameType,
			long minSendTime,
			long maxSendTime, 
			String ip , 
			long userId,
			long returnUserId) 
	{
		if(pageNo <= 0)
			pageNo = 1 ;
		
		List<MessageBean> list = new ArrayList<MessageBean>(20) ;
		PageInfo pageInfo = new PageInfo(0,0);
		PageList pageList = new PageList() ;
		pageList.setList(list) ;
		pageList.setPageInfo(pageInfo) ;
		
		long accountId = -1 ;
		
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select * from " + TableMeta.table_message +
							" where 1=1 " ;

			String countSql = "select count(*) from " + TableMeta.table_message +
							" where 1=1 " ;			
			String condition = "" ;
			
			if (AccountBean.isValidFormat(account))
			{	
				AccountBean accountBean = abb.get(account) ;
				if(accountBean == null)
					return pageList ;
				accountId = accountBean.getAccountId() ;
			}
			if (userId > 0)
				condition += " and " + TableMeta.column_user_id + " = "+ userId ;
			if (returnUserId > 0)
				condition += " and " + TableMeta.column_return_user_id + " = " + returnUserId ;
			if (accountId > 0)
				condition += " and " + TableMeta.column_account_id + " = "+ accountId ;
			if(filterRight)
				condition += " and " + TableMeta.column_status + " != " + MessageStatus.ANSWERED.status ;

			if (msgId > 0)
				condition += " and " + TableMeta.column_msg_id + " = " + msgId ; 
			if (gameType > 0)
				condition += " and " + TableMeta.column_game_type + " = " + gameType ;
			if (minSendTime > 0)
				condition += " and " + TableMeta.column_receive_time + " >= " + minSendTime ;
			if (maxSendTime > 0)
				condition += " and " + TableMeta.column_receive_time + " <= " + maxSendTime ;
			if (ip != null && ip.matches("[0-9\\.]{1,15}"))
				condition += " and " + TableMeta.column_ip + " like '%" + ip + "%' ";
			
			
			countSql += condition ;
			sql += condition + " order by " + TableMeta.column_msg_id; 
			
			int total = 0 ;
			ResultSet rs = null ;
			rs = stt.executeQuery(countSql) ;
			if (rs.next())
				total = rs.getInt(1) ;
			rs.close() ;
//			PageInfo pageInfo = new PageInfo(pageNo,total) ;
			pageInfo.setMaxRowCount(total) ;
			int maxPageNo = (total+PageInfo.PAGESIZE-1)/PageInfo.PAGESIZE;
			pageInfo.setMaxPage(maxPageNo);
			if (pageNo > maxPageNo)
				pageNo = maxPageNo;
			pageInfo.setCurPage(pageNo) ;
			int start = PageInfo.PAGESIZE*(pageNo-1) ;
			int end = PageInfo.PAGESIZE*pageNo ;
			rs = stt.executeQuery(sql) ;
			MessageBean message = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count < (end-start))
			{
				message = MessageBean.toMessageBean(rs);
				if (message != null)
				{
					list.add(message) ;
					count ++ ;
				}
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return pageList ;		
	}
	/**
	 * 查询答题记录
	 * 过滤条件包括:帐号、客户端、项目类型、状态、IP地址
	 * 
	 * */
	public static PageList getAnswerRecordListForSuper(int pageNo, 
			long msgId,
			String account,
			String clientName,
			int gameType,
			int status,
			String ip,
			String userName, 
			long minSendTime,
			long maxSendTime,
			long returnUserId) 
	{
		if(pageNo <= 0)
			pageNo = 1 ;
		
		long clientId = -1L ;
		long accountId = -1L ;
		long userId = -1L ;
		
		List<MessageBean> list = new ArrayList<MessageBean>(10) ;
		PageInfo pageInfo = new PageInfo(0,0);
		PageList pageList = new PageList() ;
		pageList.setList(list) ;
		pageList.setPageInfo(pageInfo) ;
		
		if (AccountBean.isValidFormat(account))
		{
			AccountBean accountBean = abb.get(account) ;
			if(accountBean == null)
				return pageList ;
			accountId = accountBean.getAccountId() ;
		}

		if (UserBean.isValidUserName(clientName))
		{
			ClientBean clientBean = getClientBuffer().getClientByName(clientName) ; 
			if (clientBean == null)
				return pageList ;
			else
				clientId = clientBean.getClientId() ;
		}

		if (UserBean.isValidUserName(userName))
		{
			UserBean userBean = getUserBuffer().getByUserName(userName) ; 
			if (userBean == null)
				return pageList ;
			else
				userId = userBean.getUserId() ;
		}

		
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select * from " + TableMeta.table_message ;

			String countSql = "select count(*) from " + TableMeta.table_message ;
	
			String condition = " where " + TableMeta.column_status + " >= 0" ;
			
			if (msgId >= 0)
				condition += " and " + TableMeta.column_msg_id + " = " + msgId ;
			if (clientId >= 0)
				condition += " and " + TableMeta.column_client_id + " = " + clientId ;
			if (accountId >= 0)
				condition += " and " + TableMeta.column_account_id + " = " + accountId ;
			if (gameType >= 0)
				condition += " and " + TableMeta.column_game_type + " = " + gameType ;
			if (status >= -1)
				condition += " and " + TableMeta.column_status + " = " + status ;
			if (ip != null && ip.length() > 0 && ip.indexOf('\'') < 0)
				condition += " and " + TableMeta.column_ip + " like '" + ip + "%'" ;
			if (userId >= 0)
				condition += " and " + TableMeta.column_user_id + " = " + userId ;
			if (returnUserId >= 0)
				condition += " and " + TableMeta.column_return_user_id + " = " + returnUserId ;
			if (minSendTime > 0)
				condition += " and " + TableMeta.column_receive_time + " >= " + minSendTime ;
			if (maxSendTime > 0)
				condition += " and " + TableMeta.column_receive_time + " <= " + maxSendTime ;
			sql += condition ;
			countSql += condition ;
			sql += " order by " + TableMeta.column_msg_id; 
			
			int total = 0 ;
			ResultSet rs = null ;
			rs = stt.executeQuery(countSql) ;
			if (rs.next())
				total = rs.getInt(1) ;
			rs.close() ;
			pageInfo.setMaxRowCount(total) ;
			pageInfo.setCurPage(pageNo) ;
			pageInfo.setMaxPage((total+PageInfo.PAGESIZE-1)/PageInfo.PAGESIZE);
			int start = PageInfo.PAGESIZE*(pageNo-1) ;
			int end = PageInfo.PAGESIZE*pageNo ;
			rs = stt.executeQuery(sql) ;
			MessageBean message = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count < (end-start))
			{
				message = MessageBean.toMessageBean(rs);
				if (message != null)
				{
					list.add(message) ;
					count ++ ;
				}
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return pageList ;		
	}	
	public static PageList getGameTypeList(int pageNo) {
		
		if(pageNo <= 0)
			pageNo = 1 ;
		
		List<GameTypeBean> list = new ArrayList<GameTypeBean>(10) ;
		PageInfo pageInfo = new PageInfo(0,0);
		PageList pageList = new PageList() ;
		pageList.setList(list) ;
		pageList.setPageInfo(pageInfo) ;
		
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select * from " + TableMeta.table_game_type + " where " + TableMeta.column_status + " >= 0 order by " + TableMeta.column_game_type_id;
			String countSql = "select count(*) from " + TableMeta.table_game_type + " where " + TableMeta.column_status + " >= 0";			

			int total = 0 ;
			ResultSet rs = null ;
			rs = stt.executeQuery(countSql) ;
			if (rs.next())
				total = rs.getInt(1) ;
			rs.close() ;
//			PageInfo pageInfo = new PageInfo(pageNo,total) ;
			pageInfo.setMaxRowCount(total) ;
			pageInfo.setCurPage(pageNo) ;
			pageInfo.setMaxPage((total+PageInfo.PAGESIZE-1)/PageInfo.PAGESIZE);
			int start = PageInfo.PAGESIZE*(pageNo-1) ;
			int end = PageInfo.PAGESIZE*pageNo ;
			rs = stt.executeQuery(sql) ;
			GameTypeBean gameType = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count < (end-start))
			{
				gameType = GameTypeBean.toGameType(rs);
				if (gameType != null)
				{
					list.add(gameType) ;
					count ++ ;
				}
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return pageList ;		
	}
	public static void removeClient(long clientId){
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "delete from  " + TableMeta.column_status 
						+" where " + TableMeta.column_client_id + " = " + clientId;
			stt.executeUpdate(sql) ;
			cbb.removeClient(clientId) ;
		
			stt.close() ;	
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return  ;
	}
	public static void removeGameType(int gameType){
		
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "update " + TableMeta.table_game_type + " set " + TableMeta.column_status + " = -1"
						+" where " + TableMeta.column_game_type + " = " + gameType;
			stt.executeUpdate(sql) ;
			GameTypeBean gameTypeBean = gtc.get(gameType) ;
			if(gameTypeBean != null)
				gameTypeBean.setDeleted() ;			
			stt.close() ;	
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return  ;	
	}
	public static boolean logger(long curTime, String operation, String opera_A, String opera_B,
			String opera_C, String operator)
	{
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "insert into " + TableMeta.table_logger + " values( " +
								curTime + ",'" + operation + "','" + opera_A+"','"+opera_B+"','"+
								opera_C+"','"+operator+"')";
			stt.executeUpdate(sql) ;
			stt.close() ;	
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()+"\n"+curTime+","+operation+","
					+opera_A+","+opera_B+","+opera_C+","+operator) ;
			return false ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}		
		return true ;
	}
	
	/**
	 * 查询充值记录
	 * 
	 * */
	public static PageList getLoggerList(long startTime, long endTime, String operation,
			String opera_A, String opera_B, String opera_C, String operator, int pageNo)
	{
		if(pageNo <= 0)
			pageNo = 1 ;
		
		List<LoggerRecordBean> list = new ArrayList<LoggerRecordBean>(20) ;
		PageInfo pageInfo = new PageInfo(0,0);
		PageList pageList = new PageList() ;
		pageList.setList(list) ;
		pageList.setPageInfo(pageInfo) ;
		
		
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "select * from " + TableMeta.table_logger ;
			String countSql = "select count(*) from " + TableMeta.table_logger ;
			
			String condition = " where 1=1" ;
			
			if (startTime > 0)
				condition += " and " + TableMeta.column_cur_time + " >= " + startTime ;
			if (endTime > 0)
				condition += " and " + TableMeta.column_cur_time + " <= " + endTime ;
			if (operation != null && operation.length() > 0)
				condition += " and " + TableMeta.column_operation + " = '" + operation+"'" ;
			if (operator != null && operator.length() > 0)
				condition += " and " + TableMeta.column_operator + " = '" + operator+"'" ;
			if (opera_A != null && opera_A.length() > 0)
				condition += " and " + TableMeta.column_opera_A + " = '" + opera_A+"'" ;
			if (opera_B != null && opera_B.length() > 0)
				condition += " and " + TableMeta.column_opera_B + " = '" + opera_B+"'" ;
			if (opera_C != null && opera_C.length() > 0)
				condition += " and " + TableMeta.column_opera_C + " = '" + opera_C+"'" ;
			
			
			countSql += condition ;
			sql += condition + " order by " + TableMeta.column_cur_time; 
			
			int total = 0 ;
			ResultSet rs = null ;
			rs = stt.executeQuery(countSql) ;
			if (rs.next())
				total = rs.getInt(1) ;
			rs.close() ;
			pageInfo.setMaxRowCount(total) ;
			int maxPageNo = (total+PageInfo.PAGESIZE-1)/PageInfo.PAGESIZE;
			pageInfo.setMaxPage(maxPageNo);
			if (pageNo > maxPageNo)
				pageNo = maxPageNo;
			pageInfo.setCurPage(pageNo) ;
			int start = PageInfo.PAGESIZE*(pageNo-1) ;
			int end = PageInfo.PAGESIZE*pageNo ;
			rs = stt.executeQuery(sql) ;
			LoggerRecordBean loggerRecord = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count < (end-start))
			{
				loggerRecord = LoggerRecordBean.toLoggerRecordBean(rs) ;
				if (loggerRecord != null)
				{
					list.add(loggerRecord) ;
					count ++ ;
				}
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return pageList ;		
	}
	
	
	public static GameTypeBean updateGameType(int gameType,String gameDesc, int point,
			double pointWorker,int answerType,int answerLen,int interval, int transOn,
			double difficulty)
	{
		Connection conn = null ;
		GameTypeBean gameTypeBean = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "update " + TableMeta.table_game_type + " set " +
								TableMeta.column_game_description + " = '" + gameDesc +"',"+
								TableMeta.column_point_per + " = " + point + ","+
								TableMeta.column_point_worker + " = " + pointWorker + ","+
								TableMeta.column_answer_type + " = " + answerType + ","+
								TableMeta.column_answer_length + " = " + answerLen + ","+
								TableMeta.column_min_interval + " = " + interval + ","+
								TableMeta.column_trans_on + " = " + transOn +","+
								TableMeta.column_difficulty + " = " + difficulty +
								" where " + TableMeta.column_game_type + " = " + gameType;
			stt.executeUpdate(sql) ;
			gameTypeBean = gtc.get(gameType) ;
			if(gameTypeBean != null)
			{// 更新缓存
				gameTypeBean.setAnswerLen(answerLen) ;
				gameTypeBean.setAnswerType(answerType) ;
				gameTypeBean.setGameDescription(gameDesc) ;
				gameTypeBean.setPoint(point) ;
				gameTypeBean.setPoint_worker(pointWorker) ;
				gameTypeBean.setMinInterval(interval) ;
				gameTypeBean.setTransOn(transOn) ;
				gameTypeBean.setDifficulty(difficulty) ;
			}
			stt.close() ;	
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
			gameTypeBean = null ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return gameTypeBean;
	}
	public static void uninit() 
	{
		ms.stopIt() ;
		cs.stopIt() ;
		us.stopIt() ;
		as.stopIt() ;
		rs.stopIt() ;
		sc.stopIt() ;
		try 
		{
			while(ms.isAlive() || cs.isAlive() || us.isAlive() ||
				as.isAlive() || rs.isAlive() || sc.isAlive())
				Thread.sleep(1000) ;
		} catch (InterruptedException e) {
				e.printStackTrace();
		}
		
//		if (fileServer_ctc != null)
//			fileServer_ctc.stopServer() ;
//		if (fileServer_cucc != null)
//			fileServer_cucc.stopServer() ;
//		if (answerServer_ctc != null)
//			answerServer_ctc.stopServer() ;
//		if (answerServer_cucc != null)
//			answerServer_cucc.stopServer() ;
//		
//		
//		while( (fileServer_ctc != null && fileServer_ctc.isAlive()) ||
//				answerServer_ctc != null && answerServer_ctc.isAlive() )
//		{
//			try {
//				Thread.sleep(1000) ;
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//		}
	}
	public synchronized static UserBean updateUser(String userName, String password,
			String newPassword, String qq, String email,
			String zhifubao, String phone) 
	{
		Connection conn = null ;
		UserBean userBean = null ;
		try
		{
			userBean = ubb.getByUserName(userName) ;
			if (userBean == null || !userBean.getPassword().equalsIgnoreCase(password))
				return null ;
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "update " + TableMeta.table_user + " set " +
								TableMeta.column_password + " = '" + newPassword +"',"+
								TableMeta.column_QQ + " = '" + qq + "',"+
								TableMeta.column_email + " = '" + email + "',"+ 
								TableMeta.column_zhifubao + " = '" + zhifubao + "',"+
								TableMeta.column_phone + " = '" + phone + "' "+
								" where " + TableMeta.column_user_id + " = " + userBean.getUserId();
			stt.executeUpdate(sql) ;
			userBean.setPassword(newPassword) ;
			userBean.setQQ(qq) ;
			userBean.setEmail(email) ;
			userBean.setPhone(phone) ;
			userBean.setZhifubao(zhifubao) ;
			stt.close() ;	
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
			userBean = null ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return userBean;
	}
	public static PageList getClientList(int pageNo, String clientName) 
	{
		if(pageNo <= 0)
			pageNo = 1 ;
		
		List<ClientBean> list = new ArrayList<ClientBean>(10) ;
		PageInfo pageInfo = new PageInfo(0,0);
		PageList pageList = new PageList() ;
		pageList.setList(list) ;
		pageList.setPageInfo(pageInfo) ;
		
		long clientId = -1L ;
		if (clientName != null && clientName.length() > 0)
		{
			ClientBean client = cbb.getClientByName(clientName) ;
			if (client == null)
				return pageList ;
			clientId = client.getClientId() ;
		}
		
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String condition = " where " + TableMeta.column_status + " >= 0" ;
			String sql = "select * from " + TableMeta.table_client ;
			String countSql = "select count(*) from " + TableMeta.table_client ;			
			if (clientId > 0L)
				condition += " and " + TableMeta.column_client_id + " = " + clientId ;
			
			
			sql += condition + " order by " + TableMeta.column_client_id;
			countSql += condition ;

			int total = 0 ;
			ResultSet rs = null ;
			rs = stt.executeQuery(countSql) ;
			if (rs.next())
				total = rs.getInt(1) ;
			rs.close() ;
//			PageInfo pageInfo = new PageInfo(pageNo,total) ;
			pageInfo.setMaxRowCount(total) ;
			pageInfo.setCurPage(pageNo) ;
			pageInfo.setMaxPage((total+PageInfo.PAGESIZE-1)/PageInfo.PAGESIZE);
			int start = PageInfo.PAGESIZE*(pageNo-1) ;
			int end = PageInfo.PAGESIZE*pageNo ;
			rs = stt.executeQuery(sql) ;
			ClientBean gameType = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count < (end-start))
			{
				gameType = ClientBean.toClientBean(rs) ;
				if (gameType != null)
				{
					list.add(gameType) ;
					count ++ ;
				}
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return pageList ;		
	}
	public static ClientBean updateClient(long clientId, String password,
			String name, String phone) 
	{
		Connection conn = null ;
		ClientBean clientBean = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "update " + TableMeta.table_client + " set " +
								TableMeta.column_password + " = '" + password +"',"+
								TableMeta.column_name + " = '" + name + "',"+
								TableMeta.column_phone + " = '" + phone + "'" +
								" where " + TableMeta.column_client_id + " = " + clientId;
			stt.executeUpdate(sql) ;
			clientBean = cbb.getClient(clientId) ;
			if(clientBean != null)
			{// 更新缓存
				clientBean.setPassword(password) ;
				clientBean.setPhone(phone) ;
				clientBean.setName(name) ;
			}
			stt.close() ;	
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
			clientBean = null ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		
		return clientBean;
	}
	public static PageList getUserList(int pageNo, String userName) {
		if(pageNo <= 0)
			pageNo = 1 ;
		
		List<UserBean> list = new ArrayList<UserBean>(10) ;
		PageInfo pageInfo = new PageInfo(0,0);
		PageList pageList = new PageList() ;
		pageList.setList(list) ;
		pageList.setPageInfo(pageInfo) ;
		
		long userId = -1L ;
		if (userName != null && userName.length() > 0)
		{
			UserBean user = ubb.getByUserName(userName) ;
			if (user == null)
				return pageList ;
			userId = user.getUserId() ;
		}
		
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String condition = " where " + TableMeta.column_status + " >= 0" ; ;
			String sql = "select * from " + TableMeta.table_user ;
			String countSql = "select count(*) from " + TableMeta.table_user ;			
			if (userId >= 0L)
				condition += " and " + TableMeta.column_user_id + " = " + userId ;
			
			
			sql += condition + " order by " + TableMeta.column_user_id;
			countSql += condition ;

			int total = 0 ;
			ResultSet rs = null ;
			rs = stt.executeQuery(countSql) ;
			if (rs.next())
				total = rs.getInt(1) ;
			rs.close() ;
//			PageInfo pageInfo = new PageInfo(pageNo,total) ;
			pageInfo.setMaxRowCount(total) ;
			pageInfo.setCurPage(pageNo) ;
			pageInfo.setMaxPage((total+PageInfo.PAGESIZE-1)/PageInfo.PAGESIZE);
			int start = PageInfo.PAGESIZE*(pageNo-1) ;
			int end = PageInfo.PAGESIZE*pageNo ;
			rs = stt.executeQuery(sql) ;
			UserBean user = null ;
			if (start > 0)
				rs.absolute(start) ;
			int count = 0 ;
			while(rs.next() && count < (end-start))
			{
				user = UserBean.toUserBean(rs);
				if (user != null)
				{
					list.add(user) ;
					count ++ ;
				}
			}
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return pageList ;		
	}
	public static void removeUser(long userId) 
	{
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			String sql = "update " + TableMeta.table_user + " set " + TableMeta.column_status + " = -1"
						+" where " + TableMeta.column_user_id + " = " + userId;
			stt.executeUpdate(sql) ;
			UserBean user = ubb.getById(userId) ;
			if(user != null)
				user.setDeleted() ;
			stt.close() ;	
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return  ;	
	}
	public static PageList getStasticClientList(int pageNo, String clientName,
			String minStasticTime, String maxStasticTime) 
	{
		if(pageNo <= 0)
			pageNo = 1 ;
		
		List<StasticClientBean> list = new ArrayList<StasticClientBean>(10) ;
		PageInfo pageInfo = new PageInfo(0,0);
		PageList pageList = new PageList() ;
		pageList.setList(list) ;
		pageList.setPageInfo(pageInfo) ;
		
		long clientId = -1L ;
		if (clientName != null && clientName.length() > 0)
		{
			ClientBean client = cbb.getClientByName(clientName) ;
			if (client == null)
				return pageList ;
			clientId = client.getClientId() ;
		}
		
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			
			String condition = " where 1=1 " ;
			
			String sql = StasticClientBean.getStasticSelectSQL() ;
//			String countSql = "select count(*) from " + TableMeta.table_client ;			
			if (clientId > 0L)
				condition += " and " + TableMeta.column_client_id + " = " + clientId ;
			if (minStasticTime != null)
				condition += " and " + TableMeta.column_day + " >= '" + minStasticTime+" ' ";
			if (maxStasticTime != null)
				condition += " and " + TableMeta.column_day + " <= '" + maxStasticTime+" ' ";
			sql += condition + StasticClientBean.getStasticGropubySQL() + StasticClientBean.getHavingSQL();
			sql += " order by " + TableMeta.column_client_id;
			
//			countSql += condition ;

			int total = 0 ;
			ResultSet rs = null ;
			pageInfo.setMaxRowCount(total) ;
			pageInfo.setCurPage(pageNo) ;
			pageInfo.setMaxPage((total+PageInfo.PAGESIZE-1)/PageInfo.PAGESIZE);

			rs = stt.executeQuery(sql) ;
			StasticClientBean bean = null ;
			int count = 0 ;
			while(rs.next())
			{
				bean = StasticClientBean.toBean(rs) ;
				if (bean != null)
				{
					list.add(bean) ;
					count ++ ;
				}
			}
			pageInfo.setMaxRowCount(count) ;
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}
		return pageList ;		
	}
	/**
	 * 更新消息状态
	 * 
	 * */
	public static boolean updateMsg(String msgId, int status)
	{
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			
			String sql = "update " + TableMeta.table_message +
				" set " + TableMeta.column_status + " = " + status +
				" where " +TableMeta.column_msg_id + " = " + msgId;
			stt.executeUpdate(sql) ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
			return false ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}		
		return true;
	}
	/**
	 * 查询某个消息
	 * 
	 * */
	public static MessageBean getMsg(String msgId) 
	{
		MessageBean msg = null ;
		Connection conn = null ;
		try
		{
			conn = ConnectionPool.getConnection() ;
			Statement stt = conn.createStatement() ;
			
			String sql = "select * from " + TableMeta.table_message + " where " +
					TableMeta.column_msg_id + " = " + msgId;
			ResultSet rs = stt.executeQuery(sql) ;
			if (rs.next())
				msg = MessageBean.toMessageBean(rs) ;
			rs.close() ;
			stt.close() ;
			
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		finally
		{
			ConnectionPool.freeConn(conn) ;
		}		
		return msg;
	}
			
}
